package de.firefligher.ballergame;

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.GLU;

import de.firefligher.ballergame.gui.Gui;
import de.firefligher.ballergame.gui.GuiMainMenu;

public class BallerGame implements Runnable {
	public static boolean isRunning = false;
	public static boolean isActive = false;
	
	public static int WINDOW_HEIGHT;
	public static int WINDOW_WIDTH;
	
	private Thread mainLoop;
	
	private Gui currentGui;
	
	public BallerGame() {
		isRunning = true;
		isActive = true;
		mainLoop = new Thread(this);
		
		mainLoop.start();
	}
	
	public void shutdown() {
		isActive = false;
		isRunning = false;
	}
	
	private void initDisplay() {
		try {
			Display.setDisplayMode(new DisplayMode(640, 480));
			Display.create();
			
			Mouse.create();
			Keyboard.create();
		} catch (LWJGLException e) {
			e.printStackTrace();
		} finally {
			WINDOW_HEIGHT = 480;
			WINDOW_WIDTH = 640;
		}
	}

	public static void main(String[] args) {
		new BallerGame();
	}

	@Override
	public void run() {
		initDisplay();
		initGL();
		
		this.displayGui(new GuiMainMenu());
		
		while(isRunning) {
			Display.update();
			
			if(isActive) {
				if(Display.isCloseRequested())
					shutdown();
				
				if(Mouse.isButtonDown(0))
					this.currentGui.mouseClick(Mouse.getX(), Mouse.getY(), 0);
				else if(Mouse.isButtonDown(1))
					this.currentGui.mouseClick(Mouse.getX(), Mouse.getY(), 1);
				
				renderScene();
			}
		}
	}

	private void displayGui(Gui par1Gui) {
		currentGui = par1Gui;
		currentGui.height = WINDOW_HEIGHT;
		currentGui.width = WINDOW_WIDTH;
	}

	private void renderScene() {
		GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
		GL11.glLoadIdentity();
		
		currentGui.render();
	}

	private void initGL() {
		GL11.glEnable(GL11.GL_TEXTURE_2D);
		GL11.glShadeModel(GL11.GL_SMOOTH);
		GL11.glClearColor(0.0F, 0.0F, 0.0F, 0.0F);
		GL11.glClearDepth(1.0F);
		GL11.glEnable(GL11.GL_DEPTH_TEST);
		GL11.glDepthFunc(GL11.GL_LEQUAL);
		
		GL11.glEnable(GL11.GL_BLEND);
		GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
		
		GL11.glMatrixMode(GL11.GL_PROJECTION); 
		GL11.glLoadIdentity();
		
		GLU.gluPerspective(45.0F, WINDOW_WIDTH / WINDOW_HEIGHT, 0.1F, 100.0F);
		
		GL11.glMatrixMode(GL11.GL_MODELVIEW);
		GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);
	}
}
